<?php

namespace Home\Controller;

use Think\Controller;

class CustomMenuController extends Controller {

    public function index() {
        $this->display("UserDefinedMenu");
    }

    //获取目录列表
    public function GetMenu() {
        $menuObj = M('custommenu');
        $condition["PublicCodeID"] = 1;
        $menuData = $menuObj->where($condition)->order('pid asc, sort asc')->select();
        $data = array();
        $jsonData = array();
        if (count($menuData) == 0) {
            $wechatHelper = new WechatHelperController();
            $menuResult = $wechatHelper->get_menu();
            $menuButtonlist = $menuResult['menu']['button'];

            for ($index = 0; $index < count($menuButtonlist); $index++) {
                //一级菜单
                $name = $menuButtonlist[$index]['name'];
                $jsonData['id'] = "";
                $jsonData['text'] = $name;
                $jsonData['sort'] = $sort;
                $sort++;

                //数据库存储字段赋值
                $data['Title'] = $name;
                $data['PID'] = 0;
                $data['PublicCodeID'] = 1;
                $data['URL'] = "";
                $data['Keyword'] = "";
                $pid = $menuObj->add($data);

                //二级菜单
                $subButtonArray = $menuButtonlist[$index]['sub_button'];
                $subButtonCount = count($subButtonArray);
                if ($subButtonCount != 0) {
                    $jsonData['type'] = "";
                    $jsonData['value'] = "";
                    $children = array();
                    for ($i = 0; $i < $subButtonCount; $i++) {
                        $data['Title'] = $subButtonArray[$i]['name'];
                        $data['PID'] = $pid;
                        $data['PublicCodeID'] = 1;

                        $type = $subButtonArray[$i]['type'];
                        $children[$i]['id'] = "";
                        $children[$i]['text'] = $subButtonArray[$i]['name'];
                        $children[$i]['type'] = $type;

                        $children['sort'] = $sort;
                        $sort++;

                        $value = "";
                        switch ($type) {
                            case 'click':
                                $value = $subButtonArray[$i]['key'];
                                $data['URL'] = "";
                                if (strstr($value, "ck_")) {
                                    //如果是自动回复类型
                                    $data['Keyword'] = $this->GetReplyContent($value);
                                } else {
                                    //如果是需逻辑处理的回复类型
                                    $children[$i]['type'] = 'key';
                                    $data['Keyword'] = $value;
                                }

                                break;
                            case 'view':
                                $value = $subButtonArray[$i]['url'];
                                $data['Keyword'] = "";
                                $data['URL'] = $value;
                                break;
                            default:
                                break;
                        }
                        $children[$i]['value'] = $value;
                        $menuObj->add($data);
                    }
                    $jsonData['children'] = $children;
                } else {
                    //数据库存储字段赋值
                    $type = $menuButtonlist[$index]['type'];
                    $jsonData['type'] = $type;
                    $value;
                    switch ($type) {
                        case 'click':
                            $key = $subButtonArray[$i]['key'];
                            if (strstr($key, 'ck_')) {
                                //如果是自动回复类型
                                $value = $this->GetReplyContent($key);
                            } else {
                                //如果是需逻辑处理的回复类型
                                $value = $key;
                                $jsonData['type'] = 'key';
                            }

                            break;
                        case 'view':
                            $value = $subButtonArray[$i]['url'];
                            break;
                        default:
                            break;
                    }
                    $jsonData['value'] = $value;
                    $menuObj->add($data);
                }
            }
        } else {
            $menuTree = list_to_tree($menuData, 'ID', 'PID', 'sub_button');
            foreach ($menuTree as $ID => $children) {
                $menuArray = array();
                $menu = $children;
                $menuArray["id"] = $menu["ID"];
                $menuArray["text"] = $menu["Title"];
                $menuArray['sort'] = $menu['Sort'];
                if ($menu["URL"] == '' && $menu["Keyword"] != '') {
                    $menuArray["type"] = "click";
                    $key = $menu["Keyword"];
                    if (strstr($key, 'ck_')) {
                        //如果是自动回复类型
                        $menuArray["value"] = $this->GetReplyContent($key);
                    } else {
                        //如果是需逻辑处理的回复类型
                        $menuArray["value"] = $key;
                        $menuArray["type"] = "key";
                    }
                }
                if ($menu["Keyword"] == '' && $menu["URL"] != '') {
                    $menuArray["type"] = "view";
                    $menuArray["value"] = $menu["URL"];
                }
                $childrenArray = $menu['sub_button'];
                $childArrayForJson = array();
                foreach ($childrenArray as $children) {
                    $childMenu = array();
                    $childMenu["id"] = $children["ID"];
                    $childMenu["text"] = $children["Title"];
                    if ($children["URL"] == '' && $children["Keyword"] != '') {
                        $childMenu["type"] = "click";
                        $key = $children["Keyword"];
                        if (strstr($key, 'ck_')) {
                            //如果是自动回复类型
                            $childMenu["value"] = $this->GetReplyContent($key);
                        } else {
                            //如果是需逻辑处理的回复类型
                            $childMenu["value"] = $key;
                            $childMenu["type"] = "key";
                        }
                    }
                    if ($children["Keyword"] == '' && $children["URL"] != '') {
                        $childMenu["type"] = "view";
                        $childMenu["value"] = $children["URL"];
                    }
                    $childMenu['sort'] = $children['Sort'];
                    array_push($childArrayForJson, $childMenu);
                }
                $menuArray["children"] = $childArrayForJson;
                array_push($jsonData, $menuArray);
            }
        }
        $json = json_encode($jsonData, JSON_UNESCAPED_UNICODE);
        $this->ajaxReturn($json, 'EVAL');
    }

    public function SaveMenu() {
        try {
            $treeData = I('treeData', '', 'htmlspecialchars');
            $treeData = htmlspecialchars_decode($treeData);
            $menuObj = M('custommenu');
            if ($treeData != '') {
                //$menuObj = M('custommenu');
                //$condition["PublicCodeID"] = 1;

                $jsonArray = json_decode($treeData);
                if (count($jsonArray) != 0) {
                    //$menuData = $menuObj->where($condition)->delete(); //清除所有自定义菜单`
                    $this->clearMenuSet();
                    foreach ($jsonArray as $obj) {
                        $parent_menu = array();
                        $title = $obj->text;
                        $parent_menu['Title'] = $title;
                        $parent_menu['PublicCodeID'] = 1;
                        $parent_menu['Sort'] = $obj->sort;
                        $children = $obj->children;
                        //没有子菜单的时候直接提交此菜单
                        if (count($children) == 0) {
                            $type = $obj->type;
                            $value = $obj->value;
                            switch ($type) {
                                case 'click':
                                    $key = $this->GetKey($type, $title);
                                    $parent_menu['Keyword'] = $key;

                                    //保存自定义回复
                                    $messageType = $obj->messagetype;
                                    //$content=  $this->unescape($value);
                                    $content = $this->$value;
                                    $this->saveReplyContent($messageType, $content, $key);
                                    break;
                                case 'view':
                                    $parent_menu['URL'] = $value;
                                    break;
                                case "key":
                                    $key = $this->GetKey($type, $value);
                                    $parent_menu['Keyword'] = $key;
                                    //$parent_menu['Keyword'] = $value;
                                    break;
                                default :
                                    break;
                            }
                            $parent_menu['PID'] = 0;
                            $menuObj->add($parent_menu);
                        } else {
                            $pid = $menuObj->add($parent_menu);
                            //遍历子菜单
                            foreach ($children as $childrenMenu) {
                                $child_menu = array();
                                $title = $childrenMenu->text;
                                $child_menu['Title'] = $title;
                                $child_menu['PublicCodeID'] = 1;
                                $child_menu['PID'] = $pid;
                                $child_menu['Sort'] = $childrenMenu->sort;
                                $type = $childrenMenu->type;
                                $value = $childrenMenu->value;
                                switch ($type) {
                                    case 'click':
                                        //$child_menu['Keyword'] = $value;
                                        $key = $this->GetKey($type, $title);
                                        $child_menu['Keyword'] = $key;

                                        //保存自定义回复
                                        $messageType = $childrenMenu->messagetype;
                                        $content = $value;
                                        //$content = I('message', '', 'htmlspecialchars');
                                        //$replyKey = I('replyKey', '', 'htmlspecialchars');
                                        //$content=  $this->unescape($value);
                                        $this->saveReplyContent($messageType, $content, $key);
                                        break;
                                    case 'view':
                                        $child_menu['URL'] = $value;
                                        break;
                                    case "key":
                                        $key = $this->GetKey($type, $value);
                                        $child_menu['Keyword'] = $key;
                                        // $child_menu['Keyword'] = $value;
                                        break;
                                    default :
                                        break;
                                }
                                $menuObj->add($child_menu);
                            }
                        }
                    }
                    $this->ajaxReturn('y', 'EVAL');
                }
            }
        } catch (Exception $exc) {
            $this->ajaxReturn('n', 'EVAL');
        }
    }

    //将自定义菜单推送至微信
    public function SendToWechat() {
        try {
            $menuObj = M('custommenu');
            $condition["PublicCodeID"] = 1;
            $menuData = $menuObj->where($condition)->order('pid asc, sort asc')->select();
            $menuTree = list_to_tree($menuData, 'ID', 'PID', 'sub_button');
            $data = array();
            $buttonData = array();
            $buttonArray = array();
            $buttonData['button'] = array();
            foreach ($menuTree as $ID => $children) {
                $menuArray = array();
                $menu = $children;
                $buttonArray["name"] = $menu["Title"];
                if ($menu["URL"] == '' && $menu["Keyword"] != '') {
                    $buttonArray["type"] = "click";
                    $buttonArray["key"] = $menu["Keyword"];
                }
                if ($menu["Keyword"] == '' && $menu["URL"] != '') {
                    $buttonArray["type"] = "view";
                    $buttonArray["url"] = $menu["URL"];
                }
                $childrenArray = $menu['sub_button'];
                $childArrayForJson = array();
                foreach ($childrenArray as $children) {
                    $childMenu = array();
                    $childMenu["name"] = $children["Title"];
                    if ($children["URL"] == '' && $children["Keyword"] != '') {
                        $childMenu["type"] = "click";
                        $childMenu["key"] = $children["Keyword"];
                    }
                    if ($children["Keyword"] == '' && $children["URL"] != '') {
                        $childMenu["type"] = "view";
                        $childMenu["url"] = $children["URL"];
                    }
                    array_push($childArrayForJson, $childMenu);
                }
                $buttonArray["sub_button"] = $childArrayForJson;
                array_push($buttonData['button'], $buttonArray);
            }
            //$data["menu"]=$buttonData;
            $json = json_encode($buttonData, JSON_UNESCAPED_UNICODE);
            $wechatHelper = new WechatHelperController();
            $menuResult = $wechatHelper->create_menu($json);
            if ($menuResult["errcode"] == 0) {
                $this->ajaxReturn('y', 'EVAL');
            } else {
                $this->ajaxReturn('n', 'EVAL');
            }
        } catch (Exception $exc) {
            $this->ajaxReturn('n', 'EVAL');
        }
    }

    private function saveReplyContent($messageType, $content, $replyKey) {

        switch ($messageType) {
            case 'text':
                $this->SaveTextMessage($replyKey, $content);
                break;

            default:
                break;
        }
    }

    private function clearMenuSet() {
        $menuObj = M('custommenu');
        $condition["PublicCodeID"] = 1;
        $menuData = $menuObj->where($condition)->delete(); //清除所有自定义菜单
        
        $replyinfoObj=M('replyinfo');
        $replyinfo_Condition['PublicCodeID']=1;
        $replyinfoObj->where($replyinfo_Condition)->delete(); //清除所有自定义回复
        
        $replyTextObj=M('notictext');
        $replyText_Condition['PublicCodeID']=1;
        $replyText_Condition['MsgSource']=2;
        $replyTextObj->where($replyText_Condition)->delete(); //清除所有自定义回复文本内容
        
    }

    private function SaveTextMessage($replyKey, $content) {
        $noticeText = M('notictext');
        $data['MessageText'] = $content;
        $data['InsertTime'] = time();
        $data['PublicCodeID'] = 1;
        $data['MsgSource'] = 2;

        $noticId = $noticeText->add($data);

        $replyInfo = M('replyinfo');
        $replyData['Key'] = $replyKey;
        $replyData['MsgType'] = 1;
        $replyData['MsgId'] = $noticId;
        $replyData['UpdateTime'] = time();
        $replyData['PublicCodeID'] = 1;


        $condition['Key'] = $replyKey;
        $Id = $replyInfo->add($replyData, $condition, TRUE);
        return $Id;
    }

    private function GetKey($keyType, $str) {
        //获取字符串首字母
        load('@.PYHelper');
        switch ($keyType) {
            case 'click':
                $key = "ck_";
                break;
            case 'key':
                $str = str_replace("ky_", '', $str);
                $key = 'ky_' . $str;
                break;
        }
        if ($keyType == 'click') {
            $key = $key . \PYHelper::getInitials($str);
            return $this->CheckKey($key);
        } else {
            return $key;
        }
    }

    /**
     * 根据key查找自定义回复内容，如果没找到，直接返回key值
     * @param type $key 需要查询的key值
     * @return type 回复内容
     */
    private function GetReplyContent($key) {
        $replyInfo = M('replyinfo');
        $condition['PublicCodeID'] = 1;
        $condition['Key'] = "$key";
        $form = $replyInfo->where($condition)->find();
        if ($form) {
            switch ($form['MsgType']) {
                case 1:
                    $noticeText = M('notictext');
                    $notice_condition['ID'] = $form['MsgId'];
                    $notice = $noticeText->where($notice_condition)->find();
                    $content = $notice['MessageText'];
                    break;

                default:
                    break;
            }
        } else {
            $content = $key;
        }

        return $content;
    }

    private function CheckKey($key) {
        //去数据库查找是否已经存在对应的KEY
        $replyInfo = M('replyInfo');
        $condition['KEY'] = $key;
        $condition['PublicCodeID'] = 1;
        $result = $replyInfo->where($condition)->select();
        if ($result) {
            $key = $key . "_" . getRandChar(5);
            $this->CheckKey($key);
        } else {
            return $key;
        }
    }

    function unescape($str) {
        $ret = '';
        $len = strlen($str);
        for ($i = 0; $i < $len; $i++) {
            if ($str[$i] == '%' && $str[$i + 1] == 'u') {
                $val = hexdec(substr($str, $i + 2, 4));
                if ($val < 0x7f)
                    $ret .= chr($val);
                else if ($val < 0x800)
                    $ret .= chr(0xc0 | ($val >> 6)) . chr(0x80 | ($val & 0x3f));
                else
                    $ret .= chr(0xe0 | ($val >> 12)) . chr(0x80 | (($val >> 6) & 0x3f)) . chr(0x80 | ($val & 0x3f));
                $i += 5;
            }
            else if ($str[$i] == '%') {
                $ret .= urldecode(substr($str, $i, 3));
                $i += 2;
            } else
                $ret .= $str[$i];
        }
        return $ret;
    }

    function escape($str) {
        preg_match_all("/[/x80-/xff].|[/x01-/x7f]+/", $str, $r);
        $ar = $r[0];
        foreach ($ar as $k => $v) {
            if (ord($v[0]) < 128)
                $ar[$k] = rawurlencode($v);
            else
                $ar[$k] = "%u" . bin2hex(iconv("GB2312", "UCS-2", $v));
        }
        return join("", $ar);
    }

}
